package com.lqm.service.home.impl;

import com.lqm.dao.UserAddressDao;
import com.lqm.entity.home.HomeUser;
import com.lqm.entity.home.UserAddress;
import com.lqm.service.home.UserAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

/**
 * @program: CrowdFunding
 * @description
 * @author: lqm
 * @create: 2018-12-09 16:26
 */
@Service
@Transactional
public class UserAddressServiceImpl implements UserAddressService {

    @Autowired
    UserAddressDao userAddressDao;

    @Override
    public List<UserAddress> findAll(HomeUser user) {
        return userAddressDao.findAllByHomeUser(user);
    }

    @Override
    public long getCount() {
        return userAddressDao.count();
    }

    @Override
    public UserAddress save(UserAddress userAddress) {
        return userAddressDao.save(userAddress);
    }

    @Override
    public void setUserAddressStatus(UserAddress userAddress, int status) {
        userAddressDao.setUserAddressStatus(userAddress, status);
    }

    @Override
    public UserAddress delUserAddress(UserAddress userAddress) {
        userAddressDao.deleteById(userAddress.getAddressId());

        return userAddress;
    }

    @Override
    public void setDefaultUserAddress(UserAddress userAddress, HomeUser homeUser) {

        List<UserAddress> userAddressList = userAddressDao.findAllByHomeUser(homeUser);
        for (UserAddress address : userAddressList) {
            if (userAddress.getAddressId() == address.getAddressId()) {
                address.setIsDefault(1);
            } else {
                address.setIsDefault(0);
            }

            userAddressDao.save(address);
        }
/*
        userAddress.setIsDefault(1);
        userAddressDao.save(userAddress);
*/

    }

    @Override
    public UserAddress findAllByAddressId(Integer id) {
        return userAddressDao.findAllByAddressId(id);
    }

    @Override
    public UserAddress updateAddress(UserAddress userAddress) {
        UserAddress one = userAddressDao.getOne(userAddress.getAddressId());

        return userAddressDao.save(userAddress);
    }
}
